// pages/product-detail/index.ts
import { getProductDetail } from '../../services/product';
import { addToCart } from '../../services/cart';

// 属性值类型
interface AttributeValue {
  id: number;
  value: string;
  status: number;
  createdAt: string;
  updatedAt: string;
}

// 属性类型
interface Attribute {
  id: number;
  name: string;
  values: AttributeValue[];
}

// 变体属性值类型
interface VariantAttributeValue {
  attId: number;
  valueId: number;
}

// 变体(SKU)类型
interface Variant {
  id: number;
  attValues: VariantAttributeValue[];
  code: string;
  price: number;
  stock: number;
  status: number;
}

// 商品类型
interface Product {
  id: number;
  type: number;
  title: string;
  price: number;
  image: string;
  description: string;
  stock: number;
  sales: number;
  status: number;
  category: {
    id: number;
    name: string;
  };
  attributes: Attribute[];
  variants: Variant[];
  [key: string]: any;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productId: 0,
    product: {} as unknown as Product,
    count: 1,
    loading: false,
    // 存储已选属性
    selectedAttrs: {} as Record<number, number>,
    // 当前选中的变体
    currentVariant: null as Variant | null
  },

  /**
   * 获取商品详情
   */
  async fetchProductDetail(id: number) {
    try {
      this.setData({ loading: true });
      const res = await getProductDetail(id);
      if (res.code === 0) {
        // 将API返回的数据转换为我们定义的类型
        const product = res.data as unknown as Product;
        
        this.setData({ 
          product: product,
        });
        
        // 如果有变体，默认选择第一个
        if (product.variants && product.variants.length > 0) {
          // 初始化已选属性
          const initialSelectedAttrs: Record<number, number> = {};
          
          // 获取第一个变体的属性值
          const firstVariant = product.variants[0];
          firstVariant.attValues.forEach((av: VariantAttributeValue) => {
            initialSelectedAttrs[av.attId] = av.valueId;
          });
          
          this.setData({ 
            selectedAttrs: initialSelectedAttrs,
            currentVariant: firstVariant
          });
        }
      }
    } catch (error) {
      console.error('获取商品详情失败', error);
      wx.showToast({
        title: '获取商品详情失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 数量增加
   */
  handleAddCount() {
    this.setData({
      count: this.data.count + 1
    });
  },

  /**
   * 数量减少
   */
  handleReduceCount() {
    if (this.data.count > 1) {
      this.setData({
        count: this.data.count - 1
      });
    }
  },

  /**
   * 选择属性值
   */
  handleSelectAttr(e: WechatMiniprogram.TouchEvent) {
    const { attId, valueId } = e.currentTarget.dataset;
    
    // 更新已选属性
    const newSelectedAttrs = { ...this.data.selectedAttrs };
    newSelectedAttrs[attId] = valueId;
    
    // 查找匹配的变体
    const matchedVariant = this.findMatchingVariant(newSelectedAttrs);
    
    this.setData({
      selectedAttrs: newSelectedAttrs,
      currentVariant: matchedVariant
    });
  },

  /**
   * 根据已选属性查找匹配的变体
   */
  findMatchingVariant(selectedAttrs: Record<number, number>): Variant | null {
    const { product } = this.data;
    
    if (!product.variants || product.variants.length === 0) {
      return null;
    }
    
    // 获取已选属性数量
    const selectedAttrsCount = Object.keys(selectedAttrs).length;
    
    // 查找完全匹配的变体
    return product.variants.find(variant => {
      // 变体属性数量必须匹配
      if (variant.attValues.length !== selectedAttrsCount) {
        return false;
      }
      
      // 所有属性值必须匹配
      return variant.attValues.every(av => 
        selectedAttrs[av.attId] === av.valueId
      );
    }) || null;
  },

  /**
   * 检查属性值是否选中
   */
  isAttributeValueSelected(attId: number, valueId: number): boolean {
    return this.data.selectedAttrs[attId] === valueId;
  },

  /**
   * 加入购物车
   */
  handleAddToCart() {
    const { product, count, currentVariant } = this.data;
    
    if (!product.id) {
      wx.showToast({
        title: '商品信息不完整',
        icon: 'none'
      });
      return;
    }
    
    // 检查是否选择了所有需要的属性
    if (product.attributes && product.attributes.length > 0) {
      const selectedAttrsCount = Object.keys(this.data.selectedAttrs).length;
      
      if (selectedAttrsCount !== product.attributes.length) {
        wx.showToast({
          title: '请选择所有规格',
          icon: 'none'
        });
        return;
      }
      
      if (!currentVariant) {
        wx.showToast({
          title: '所选规格无效',
          icon: 'none'
        });
        return;
      }
    }
    
    // 构建SKU名称
    let skuName = '';
    if (currentVariant && product.attributes) {
      const skuNames = currentVariant.attValues.map(av => {
        const attr = product.attributes.find(a => a.id === av.attId);
        if (!attr) return '';
        
        const value = attr.values.find(v => v.id === av.valueId);
        return value ? `${attr.name}: ${value.value}` : '';
      });
      
      skuName = skuNames.filter(Boolean).join(', ');
    }
    
    // 添加到购物车
    addToCart({
      id: product.id,
      title: product.title,
      price: currentVariant ? currentVariant.price : product.price,
      image: product.image || '../../asssets/logo.png',
      count: count,
      skuId: currentVariant ? currentVariant.id : undefined,
      skuName: skuName || undefined
    });
    
    // 提示成功并返回上一页
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    });
    
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      const id = parseInt(options.id);
      this.setData({
        productId: id
      });
      this.fetchProductDetail(id);
    } else {
      wx.showToast({
        title: '商品ID不存在',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if (this.data.productId) {
      this.fetchProductDetail(this.data.productId);
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.product.title || '商品详情',
      path: `/pages/product-detail/index?id=${this.data.productId}`
    };
  }
})